package net.wanglu.www.spdr.dao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import net.wanglu.www.spdr.entities.Corpus;
import net.wanglu.www.spdr.log.LoggerFactory;
import net.wanglu.www.spdr.main.SpiderMain;

import org.apache.commons.lang3.time.DateFormatUtils;

public class CorpusFileDAO implements CorpusDAO {

	Marshaller marshaller = null;
	String date = null;
	String basePath = null;
	File outputDir = null;
	
	public CorpusFileDAO() {
        
		try {
			JAXBContext jc = JAXBContext.newInstance(new Class[]{net.wanglu.www.spdr.entities.Corpus.class});
	        marshaller=jc.createMarshaller(); 
	        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
	        date = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd");
			if ( SpiderMain.SpiderProperties == null || SpiderMain.SpiderProperties.getProperty("Barn") == null ) {
				basePath = "D:\\Temp\\";
			} else {
				basePath = SpiderMain.SpiderProperties.getProperty("Barn");
			}
			outputDir = new File(basePath + date);
			if ( !outputDir.exists() ) {
				outputDir.mkdirs();
			}
		} catch (JAXBException e) {
			LoggerFactory.SpiderLogger.trace("", e);
			marshaller = null;
		}  
	}
	@Override
	public Corpus findCorpus(Object query) throws Exception {
		return null;
	}

	@Override
	public boolean insertCorpus(Corpus corpus) throws Exception {
		if ( marshaller == null) {
			JAXBContext jc = JAXBContext.newInstance(new Class[]{net.wanglu.www.spdr.entities.Corpus.class});
	        marshaller=jc.createMarshaller(); 
	        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		}
		
		if ( date == null ) {
			date = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd");
		}
		
		if ( basePath == null ){
			basePath = SpiderMain.SpiderProperties.getProperty("Barn");
		}
		
		if ( outputDir == null || !outputDir.exists() ) {
			outputDir = new File(basePath + date);
			outputDir.mkdirs();
		}

		
		String fileName = String.valueOf(System.currentTimeMillis());
        FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(basePath+date+File.separator+fileName+".xml");
			marshaller.marshal( corpus, fos);
		} catch (FileNotFoundException e) {
			LoggerFactory.SpiderLogger.trace(corpus.getSource()+"写入失败", e);
		} catch (JAXBException e) {
			LoggerFactory.SpiderLogger.trace(corpus.getSource()+"写入失败", e);
		} finally {
			if ( fos != null ){
				try{
					fos.close();
				} catch ( IOException e) {
					LoggerFactory.SpiderLogger.trace("", e);
				}
			}
		}

		return true;
	}
}
